# from .WXBizDataCrypt import WXBizDataCrypt
from .models import User
import re
from django.contrib.auth.backends import ModelBackend
# from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
from django.conf import settings
from . import constants
from django.db.models import Q
import requests
import random
import string

class OpenidUtils(object):
    def __init__(self, jscode):
        self.url = "https://api.weixin.qq.com/sns/jscode2session"
        self.appid = settings.WECHAT_APP_ID
        self.secret = settings.WECHAT_APP_KEY
        self.jscode = jscode  # 前端传回的动态jscode

    def get_openid(self):
        url = self.url + "?appid=" + self.appid + "&secret=" + self.secret + "&js_code=" + self.jscode + "&grant_type=authorization_code"
        r = requests.get(url)
        openid = r.json()['openid']
        return openid

    def random_str(self,num):
        random_str = ''.join(random.sample(string.ascii_letters + string.digits, num))
        return random_str

#
# def generate_mobile(appid, sessionKey, encryptedData, iv):
#     pc = WXBizDataCrypt(appid, sessionKey)
#     return pc.decrypt(encryptedData, iv)


# class OAuthWechat(object):
#     """
#      微信认证辅助工具类
#      """
#
#     @staticmethod
#     def generate_save_user_token(openid):
#         """
#         生成保存用户数据的token
#         :param openid: 用户的openid
#         :return: token
#         """
#         serializer = TJWSSerializer(settings.SECRET_KEY, expires_in=constants.SAVE_WECHAT_USER_TOKEN_EXPIRES)
#         data = {'openid': openid}
#         token = serializer.dumps(data)
#         return token.decode()
